package cn.hg.solon.youcan.framework.directive.system;

import static cn.hg.solon.youcan.system.entity.table.SysDictItemTableDef.SYS_DICT_ITEM;

import java.util.List;
import java.util.function.Supplier;

import org.apache.ibatis.solon.annotation.Db;
import org.dromara.hutool.core.text.StrValidator;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import com.jfinal.template.Env;
import com.jfinal.template.TemplateException;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import com.mybatisflex.core.query.QueryOrderBy;
import com.mybatisflex.core.query.QueryWrapper;

import cn.hg.solon.youcan.common.constant.CacheConstants;
import cn.hg.solon.youcan.common.enums.BeanStatus;
import cn.hg.solon.youcan.framework.cache.YoucanCacheService;
import cn.hg.solon.youcan.framework.directive.BaseDirective;
import cn.hg.solon.youcan.system.entity.SysDictItem;
import cn.hg.solon.youcan.system.mapper.SysDictItemMapper;

/**
 * @author 胡高
 */
@Component("view:" + DictsDirective.DIRECTIVE_NAME)
public class DictsDirective extends BaseDirective {

    public static final String DIRECTIVE_NAME = "DICTS";

    @Db
    SysDictItemMapper dictItemMapper;

    @Inject
    YoucanCacheService cacheService;

    @Override
    public boolean hasEnd() {
        return true;
    }

    @Override
    public void onRender(Env env, Scope scope, Writer writer) {
        String type = this.getParaToString(0, scope);
        if (StrValidator.isBlank(type)) {
            throw new TemplateException("The parameter of #" + DIRECTIVE_NAME + " directive can not be blank",
                this.location);
        }

        /*
         * 查询DICT_ITEM
         */
        List<SysDictItem> list = this.cacheService.getOrStoreTag(DIRECTIVE_NAME + ":" + type, CacheConstants.CACHE_SECONDS_ONE_DAY, new Supplier<List<SysDictItem>>() {
            @Override
            public List<SysDictItem> get() {
                return DictsDirective.this.dictItemMapper.selectListByQuery(QueryWrapper.create()
                    .where(SYS_DICT_ITEM.STATUS.eq(BeanStatus.ON.name()).and(SYS_DICT_ITEM.TYPE.eq(type)))
                    .orderBy(new QueryOrderBy(SYS_DICT_ITEM.SORT))
                    );
            }

        } , CacheConstants.SYS_DICT_TAG);

        scope.setLocal(this.getPara("var", scope, DIRECTIVE_NAME.toLowerCase()), list);

        this.renderBody(env, scope, writer);
    }

}
